package cn.ibdsr.human.util;

import cn.ibdsr.human.constant.BizConstants;
import cn.ibdsr.human.constant.OrderFieldEnum;
import cn.ibdsr.human.transfer.PageQuery;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lvyou
 * @description:
 * @date: 2020/3/20
 * @lastModified: 最后修改人
 * <p>
 * Date           Author               Description
 * ------------------------------------------------------
 * 2020/3/20       lvyou                修改记录
 */
public class MybatisPlusPage<T> {

    public static <T> Page<T> defaultNewPage(PageQuery pagination) {
        Long pageIndex = pagination.getPageNo();
        Long size = pagination.getPageSize();
        Page<T> page = new Page<>();
        if (pageIndex != null && pageIndex > 0 && size != null && size > 0) {
            page.setCurrent(pageIndex);
            if (size > BizConstants.MAX_PAGE_SIZE) {
                return null;
            }
            page.setSize(size);
        }
        if (StringUtils.isNotEmpty(pagination.getSortField()) && OrderFieldEnum.valueOf(pagination.getSortField()) != null) {
            String sortField = OrderFieldEnum.valueOf(pagination.getSortField()).getFieldName();
            Boolean isAsc = "asc".equals(pagination.getSortOrder());
            if (StringUtils.isNotEmpty(sortField)) {
                List<OrderItem> orders = new ArrayList<>();
                OrderItem orderItem = new OrderItem();
                orderItem.setColumn(sortField);
                orderItem.setAsc(isAsc);
                orders.add(orderItem);
                page.setOrders(orders);
            }
        }
        return page;
    }
}
